<?php

namespace App\Custom;

use App\Constants\Code;
use Hyperf\Paginator\AbstractPaginator;
use Hyperf\Validation\Validator;
use function Hyperf\Translation\trans;

/**
 * API 的结果统一返回方法
 */
trait ApiResponse
{
    /**
     * 成功的响应
     * @param array $data
     * @param string $message
     * @return array
     */
    public function ok(array $data = [] ,string $message = 'OK')
    {
        return [
            "code" => 0 ,
            "msg" => $message,
            "data" => $data,
        ];
    }

    /**
     * 出错的响应
     * @param int $code
     * @param string $message
     * @param array $data
     * @return array
     */
    public function error(int $code , string $message = '', array $data = [] )
    {
        return [
            "code" => $code ,
            "msg" =>   trans(sprintf("code.%d",$code)),
            "data" => $data,
        ];
    }

    /**
     * 验证失败返回
     * @param Validator $validator
     * @return array
     */
    public function invalid(Validator $validator)
    {
        return [
            "code" => Code::VALIDATE_FAIL,
            "msg" => trans(sprintf("code.%d",Code::VALIDATE_FAIL)),
            "data" => [
                "errors" => $validator->errors()
            ],
        ];
    }

    /**
     * 根据分页对象响应分页结果
     * @param AbstractPaginator $paginated
     * @return array
     */
    public function paginator(AbstractPaginator $paginated)
    {
        return [
            "code" => Code::OK,
            "msg" => trans(sprintf("code.%d",Code::OK)),
            "data"=>[
                "list" => $paginated->items(),
                "paginate"=>[
                    "total" => $paginated->total(),
                    "page" => $paginated->currentPage(),
                    "page_size" =>$paginated->perPage(),
                ]
            ]
        ];
    }
}
